import csv
import requests
import time
import base64
import random
import hashlib


def fetch_movie_data(order_type='0', uuid='192766208a2c8-0286a30a18f6a4-4c657b58-168000-192766208a2c8'):
    url = "https://piaofang.maoyan.com/dashboard-ajax/movie"
    headers = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 '
                      'Safari/537.36 Edg/129.0.0.0',
        'Cookie': '_lxsdk_cuid=1948ce6c81bc8-090731d3fa23cf-26011851-168000-1948ce6c81bc8; _lxsdk=1948ce6c81bc8-090731d3fa23cf-26011851-168000-1948ce6c81bc8; _lxsdk_s=19563b86a7e-b4a-991-014%7C%7C1',
        "Referer": "https://piaofang.maoyan.com/dashboard/movie?movieId=1491310"
    }

    timestamp = str(int(time.time() * 1000))
    user_agent = b"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
    User_Agent = base64.b64encode(user_agent).decode()
    index = str(int(random.random() * 10000) + 1)
    content = f'method=GET&timeStamp={timestamp}&index={index}&userAgent={User_Agent}&channelId=40009&sVersion=2&signKey=1388e4f3c1fdd2850eb193d1e44b2f79'
    sign = hashlib.md5(content.encode()).hexdigest()

    params = {
        'orderType': order_type,
        'uuid': uuid,
        'timeStamp': timestamp,
        'User-Agent': User_Agent,
        'index': index,
        'channelId': '40009',
        'sVersion': '2',
        'signKey': sign,
    }

    response = requests.get(url, params=params, headers=headers).json()
    data_list = response['movieList']['list']

    movie_office_list = []
    for i, movie in enumerate(data_list, start=1):
        # 获取电影名称
        movie_name = movie['movieInfo']['movieName']
        # 获取电影发行信息
        movie_releaseInfo = movie['movieInfo']['releaseInfo']
        # 获取电影分账票房比例
        movie_splitBoxRate = movie['splitBoxRate']
        # 获取电影排片场次
        movie_showCount = movie['showCount']
        # 获取电影排片场次占比
        movie_showCountRate = movie['showCountRate']
        # 获取电影累计票房描述
        movie_sumBoxDesc = movie['sumBoxDesc']

        movie_office_list.append(
            [i, movie_name, movie_releaseInfo, movie_splitBoxRate, movie_showCount, movie_showCountRate,
             movie_sumBoxDesc])

    return movie_office_list


def save_to_csv(movie_data, filename='reptile_data.csv'):
    with open(filename, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        # 写入表头
        writer.writerow(['ID', 'MovieName', 'ReleaseInfo', 'SplitBoxRate', 'ShowCount', 'ShowCountRate', 'SumBoxDesc'])
        # 写入数据
        writer.writerows(movie_data)


if __name__ == '__main__':
    # 调用函数并打印结果
    movie_data = fetch_movie_data()
    print(movie_data)
    save_to_csv(movie_data)
